import com.github.facadefs.FileSystem;
import com.github.facadefs.FileView;
import com.github.facadefs.Operations;
import com.github.facadefs.local.LocalFileSystem;
import com.github.facadefs.sftp.JschSftpFileSystem;
import com.github.facadefs.util.IOUtils;
import com.github.facadefs.util.Operation;
import com.google.common.collect.Lists;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author changhe.yang
 * @since 20240522
 */
public class FileSystemWatcher {
    private final FileSystem fs;

    public FileSystemWatcher(final FileSystem fs) {
        this.fs = fs;
    }

    public FileView[] watchModify(final String path, final long lastWatchTimestamp) throws IOException {
        return fs.execute(new Operation<Operations, FileView[]>() {
            @Override
            public FileView[] execute(final Operations operations) throws IOException {
                return doWatchModify(operations, path, lastWatchTimestamp);
            }
        });
    }

    private FileView[] doWatchModify(final Operations op, final String path, final long lastWatchTimestamp) throws IOException {
        final FileView[] views = op.ls(path);
        final List<FileView> update = Lists.newArrayListWithExpectedSize(views.length);
        for (final FileView view : views) {
            final long lastModifiedTime = view.getLastModifiedTime();
            if (lastModifiedTime > lastWatchTimestamp) {
                update.add(view);
            }
        }
        return update.toArray(new FileView[0]);
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        /*

         */
        final FileView[] ls = new LocalFileSystem().ls("/");
        for (final FileView l : ls) {
            System.out.println(l);
        }
        System.exit(0);

        final InputStream in = FileSystemWatcher.class.getResourceAsStream("");
        final byte[] privateKey = IOUtils.readBytes(in, true);

        final JschSftpFileSystem fs = new JschSftpFileSystem();
        fs.setHost("");
        fs.setUsername("");
        fs.setPassword("");
        fs.setPrivateKey(privateKey);

//        fs.setHost("");
//        fs.setUsername("");
//        fs.setPassword("");

        final String watchPath = "/upload/JD";
        final FileSystemWatcher watcher = new FileSystemWatcher(fs);
        long lastModifyTimestamp = 0;
        while (true) {
            FileView[] fileViews = watcher.watchModify(watchPath, lastModifyTimestamp);
            for (FileView fileView : fileViews) {
                lastModifyTimestamp = Math.max(fileView.getLastModifiedTime(), lastModifyTimestamp);
                System.out.println(fileView);
            }
            Thread.sleep(5000);
        }

    }
}
